import { createRouter, createWebHashHistory } from 'vue-router'

//导入组件
import Index from '@/views/Index'
import Prodetail from '@/views/Index/Prodetail'
import Types from '@/views/Types'
import Cart from '@/views/Cart'
import Video from '@/views/Video'
import My from '@/views/My'
import Info from '@/views/My/Info'
import Address from '@/views/My/Address'
import MyIndex from '@/views/My/MyIndex'

import store from '@/store'

const routes = [
  {
    //首页
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index',
    component: Index,
  },
  {
    path: '/prodetail',
    component: Prodetail
  },
  {
    //分类
    path: '/types',
    component: Types
  },
  {
    //购物车
    path: '/cart',
    component: Cart
  },
  {
    //视频
    path: '/video',
    component: Video
  },
  {
    //我的
    path: '/my',
    component: My,
    redirect: '/my/index',
    //子路由
    children: [
      {
        path: 'index',
        component: MyIndex
      },
      {
        path: 'info',
        component: Info
      },
      {
        path: 'address',
        component: Address
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/My/Login')
  },
  {
    path: '/register',
    component: () => import('@/views/My/Register')
  }
]

// const originalPush = VueRouter.prototype.push;
// VueRouter.prototype.push = function push(location) {
//   return originalPush.call(this, location).catch((err) => err);
// };

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  // console.log(to, from);
  let arr = ['/index', '/types', '/video', '/cart', '/my/index']
  let index = arr.indexOf(to.path)
  store.commit('changeActive', index)
  next()
})

export default router
